package com.googlecode.gwtbb.client.only.glue;

import com.googlecode.gwtbb.client.shared.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 16, 2008
 */
public class PathUtils {
	public static String LINK_PREFIX = "forums";

	public static String getTokenStart(String token) {
		if (token == null)
			return null;
		int i = token.indexOf(TokenOwner.DELIM_CHR);
		int j = token.indexOf('_');
		if (i < 0 || (j < i && j >= 0)) {
			i = j;
		}
		return i < 0 ? token : token.substring(0, i);
	}

	public static String normalize(String token) {
		return token.replace(' ', '_');
	}

	public static String concatToken(Long t1, String t2) {
		return t1 + "_" + normalize(t2);
	}

	public static String makeSubToken(String pathBase, String token) {
		return pathBase + TokenOwner.DELIM_CHR + token;
	}

	public static String getSubToken(String token) {
		if (token == null)
			return null;
		int i = token.indexOf(TokenOwner.DELIM_CHR);
		return i < 0 ? null : token.substring(i + 1);
	}

	public static String plural(String name) {
		return name + "s";
	}

	public static String link(String token) {
		return makeSubToken(LINK_PREFIX, token);
	}

	public static Map<String, String> getQueryParams(String token) {
		Map<String, String> retVal = new HashMap<String, String>();
		int i = token.indexOf('?');
		if (i > 0) {
			String paramsStr = token.substring(i + 1);
			for (String nameValuePair : paramsStr.split("&")) {
				String name = null, value = null;
				if (StringUtils.isNotEmpty(nameValuePair)) {
					i = nameValuePair.indexOf('=');
					if (i > 0) {
						name = nameValuePair.substring(0, i);
						i++;
						if (i < nameValuePair.length())
							value = nameValuePair.substring(i);
					} else
						name = nameValuePair;
				}
				if (StringUtils.isNotEmpty(name))
					retVal.put(name, value);
			}
		}
		return retVal;
	}

	private PathUtils() {
	}
}
